#!/usr/bin/env sh
set -e

cd "$(realpath "$(dirname "$0")")"/ || exit 1

ymltocsvfolder() {
  YMLSPECFILE="$1"
  FOLDER="$2"

  FILES="$(cat "$YMLSPECFILE" | yq keys | cut -d ' ' -f2)"
  echo "$FILES" | while read FILE; do
    cat "$YMLSPECFILE" | yq -o=csv ".\"$FILE\"" > "$FOLDER"/"$FILE"
  done
}

ymltocsvzip() {
  INPUTYMLPATH="$1"

  CSVFOLDER="$(mktemp -d)"
  ymltocsvfolder "$INPUTYMLPATH" "$CSVFOLDER"
  ZIPFOLDER="$(mktemp -d)"
  ZIPFILE="$(basename "$INPUTYMLPATH").zip"
  cd "$ZIPFOLDER"
  zip -j "$ZIPFILE" "$CSVFOLDER"/*

  echo "Converted input YML file: <$INPUTYMLPATH> to zip <$ZIPFOLDER/$ZIPFILE>" >&2
  echo "$ZIPFOLDER"/"$ZIPFILE"
}

ymltocsvzip "mocks/gtfs_sample_0.yml"